import defaults from 'superagent-defaults';
import axios from "axios";
import qs from "qs";
import {errorHandle} from '../app/index/services/error';
import {getDataFromLocal,refererLogin} from '../app/index/services/authentication'
import MessageActions from '../components/actions/message'
import {browserHistory} from 'react-router'

const token = getDataFromLocal("token") || "";
const userId = getDataFromLocal("userId") || "";

const config = {
    baseURL: "",
    timeout: 1000 * 60 * 5,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    transformRequest: [function(data) {
        return qs.stringify(data)
    }]
}

if(token) config.headers.Token = token;
if(userId) config.headers.UserId = userId;

let jsonConfig = JSON.parse(JSON.stringify(config));
jsonConfig.headers["Content-Type"] = "application/json; charset=UTF-8";
jsonConfig.transformRequest = [function(data) {
    return JSON.stringify(data)
}]

const responseInterceptors = {
    success: function(response) {
        if(response.data.responseCode && response.data.responseCode === "A005") {
            localStorage.clear();
            refererLogin();
            return new Promise(()=>{});//token失效,不再走then,catch,finally,直接去登录页面
        }
        return response
    },
    fail: function(error) {
        errorHandle(error.status);
        return Promise.reject(error);
    },
    getToken:function (config) {
        config.headers.Token= getDataFromLocal("token");
        config.headers.UserId= getDataFromLocal("userId");
        return config;
    },
}

const request = axios.create(config);
const jsonRequest = axios.create(jsonConfig);

request.interceptors.response.use(responseInterceptors.success, responseInterceptors.fail);
jsonRequest.interceptors.response.use(responseInterceptors.success, responseInterceptors.fail);

request.interceptors.request.use(responseInterceptors.getToken, console.log);
jsonRequest.interceptors.request.use(responseInterceptors.getToken,console.log);

var superagent = defaults();

superagent
    .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    .set("Token", token)
    .set("UserId", userId)

 

//试行一个新的request类
const myResquest = axios.create(jsonConfig);
const myResquest_form = axios.create(config);
const myInterceptors = {
    success: function(res) {
        //处理登录超时
        if(res.data.responseCode === "A005") {
            localStorage.clear();
            refererLogin();
            return new Promise(()=>{});//token失效,不再走then,catch,finally,直接去登录页面
        }
        //处理是否正确code
        if (res.data.responseCode === "00") {
            return res.data.content;
        }else {
            //其他code作为错误拒绝
            return Promise.reject(res.data)
        }
    },

    fail: function(error) {
        errorHandle(error.status);
        return Promise.reject(error);
    },
    getToken:function (config) {
        config.headers.Token= getDataFromLocal("token") ||'';
        config.headers.UserId= getDataFromLocal("userId") || '';
        return config;
    },
}
myResquest.interceptors.response.use(myInterceptors.success,myInterceptors.fail);
myResquest_form.interceptors.response.use(myInterceptors.success,myInterceptors.fail);
// 请求前用方法去取token
myResquest.interceptors.request.use(myInterceptors.getToken, myInterceptors.fail);
myResquest_form.interceptors.request.use(myInterceptors.getToken, myInterceptors.fail);


export  class Http{
    s;
    c;
    f;
    y;
    method;
    url;
    params;
    request;
    constructor(type){
        if(!type || type=='json'){
            this.request=myResquest
        }else if(type=='urlencod'){
            this.request = myResquest_form ;
        }else{
            this.request = myResquest_form ;
        }
    }
    get(url,params){
        this.method = 'get'
        this.send(url,params);
        return this;
    }
    post(url,params){
        this.method = 'post'
        this.send(url,params);
        return this;
    }
    send(url,params){
        this.url = url;
        this.params =params;
        setTimeout(() => this.request[this.method](this.url, this.params).then(this.s, this.f).catch(this.c || this.complete).finally(this.y), 10);
    }
    catch(c){
        this.c=c;
        return this;
    }
    then(s,f){
        this.s=s
        this.f = f;
        return this;
    }
	finally(y){
		this.y=y;	
	}
    //当业务不处理错误时,调用该catch方法
    complete(res){
        //若可能，再次处理登录超时
        if(res.responseCode === "A005") {
            localStorage.clear();
            let referer = location.pathname+location.search;
            browserHistory.push({pathname:'/user/login',query: {referer,},});
            return;
        }
        //处理responseCode错误,网络请求错误时不处理
      
        if(res.responseCode||!res.responseCode){
        	
        	MessageActions.show({'message': res.responseMessage || "未知错误"});
        	
        }
        
    };
}


export default superagent;
export {
    request,
    jsonRequest
}